package parser

import (
	"encoding/xml"
	"io/ioutil"
	"os"
)

type Property struct {
	Name    string `xml:"name,attr"`
	Type    string `xml:"type,attr"`
	Len     int    `xml:"len,attr"`
	Save    string `xml:"save,attr"`
	Public  string `xml:"public,attr"`
	Comment string `xml:"comment,attr"`
}

type Column struct {
	Type    string `xml:"type,attr"`
	Name    string `xml:"name,attr"`
	Comment string `xml:"comment,attr"`
	Len     int    `xml:"len,attr"`
}

type Record struct {
	Name    string   `xml:"name,attr"`
	Cols    int      `xml:"cols,attr"`
	Maxrows int      `xml:"maxrows,attr"`
	Save    string   `xml:"save,attr"`
	Visible string   `xml:"visible,attr"`
	Comment string   `xml:"comment,attr"`
	Columns []Column `xml:"column"`
}

type Object struct {
	Name      string     `xml:"name"`
	Type      string     `xml:"type"`
	Base      string     `xml:"base"`
	Propertys []Property `xml:"propertys>property"`
	Records   []Record   `xml:"records>record"`
}

var (
	Defs = make(map[string]Object)
)

func ParseEntity(file string) Object {
	f, err := os.Open(file)
	if err != nil {
		panic(err)
	}

	defer f.Close()
	data, err := ioutil.ReadAll(f)
	if err != nil {
		panic(err)
	}
	var obj Object
	err = xml.Unmarshal(data, &obj)
	if err != nil {
		panic(err)
	}

	return obj
}

func LoadAllDef(path string) {
	dir, _ := os.Open(path)
	files, _ := dir.Readdir(0)

	defs := make(map[string]Object, 20)
	for _, f := range files {
		if !f.IsDir() {
			obj := ParseEntity(path + "/" + f.Name())
			defs[obj.Name] = obj
		}
	}

	Defs = defs
}
